<?php
require_once 'MySqlHelper.php';
/**
 *  <item>
 <Title><![CDATA[title]]></Title>
 <Description><![CDATA[description]]></Description>
 <PicUrl><![CDATA[picurl]]></PicUrl>
 <Url><![CDATA[url]]></Url>
 </item>
 */
class Item{
	public $_title;
	public $_description;
	public $_picUrl;
	public $_url;
	
	function getItems($sql,$needSuggest=1){
		$mysqlHelper = MySqlHelper::getInstance();
		$query = $mysqlHelper->query($sql);
		$items = array();
		while($rs=$mysqlHelper->fetch_array($query)){
			$item = new Item();
			$item->_description = str_replace("<br>", "\n", $rs['origi_msg']);
			$item->_title = $rs['title'];
			$item->_url = "http://www.qiyadeng.com/shanghaisales/weixindetail.php?id=".$rs['id'];
			$item->_picUrl = "http://www.qiyadeng.com/shanghaisales/sales.jpg";
			$items[] = $item;
		}
		if($needSuggest==1){
			$item = new Item();
			$item->_description = "\n可输入'优惠'查询最新优惠信息,也可输入商场名称(八佰伴)、地址(张杨路)、品牌(森达)查询优惠信息。";
			$item->_title = "使用帮助\n可输入'优惠'查询最新优惠信息,也可输入商场名称(八佰伴)、地址(张杨路)、品牌(森达)查询优惠信息。";
			$items[] = $item;
		}
		return $items;
	}
	
	function getShanghaiSalesItems($messageContent,$count, $needSuggest=1){
		//check if messageCotent is date
		//check if messageContent is '优惠'
		$needUpdate = 'f';
		$sql = "select max(create_time)as last_time from act_detail";
		$mysqlHelper = MySqlHelper::getInstance();
		$query = $mysqlHelper->query($sql);
		$c = $mysqlHelper->num_rows($query);
		if($c==0){
			$needUpdate = 't';
		}
		else{
			$lastTime =time();
			while($rs=$mysqlHelper->fetch_array($query)){
				$lastTime = $rs['last_time'];
			}
			$time1 = time();
			$last = strtotime($lastTime);
			if($time1 - $last>2*60*60){//2 hours
				$needUpdate ='t';
			}
		}
		if($needUpdate=='t'){
			file_get_contents("http://www.qiyadeng.com/shanghaisales/shanghaidz.php");
		}
		
		$tmparray = explode("优惠",$messageContent);
		//if(mb_strpos($messageContent, "优惠",0,"utf-8")){
		if(count($tmparray)>1){
			//check keyword
			$sql = "select id, title,origi_msg from act_detail where length(origi_msg)>0 order by create_time desc limit $count";//
			//echo $sql;
			return $this->getItems($sql);
		}
		else{
			$sql = "select id, title,origi_msg from act_detail where origi_msg like '%$messageContent%' order by create_time desc limit $count ";//TODO sql inject
			//echo $sql;
			return $this->getItems($sql);
		}
	}

}
?>